﻿using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UCS.XNA.Utils.Math;

namespace Hopeless.Metaphysical
{
    public class Player
    {
        public Player(HopelessGame game)
        {
            _game = game;
        }

        private HopelessGame _game;
        private KeyboardState _lastKeyboardState;

        public void Update(GameTime gameTime)
        {
            if (!_game.IsActive)
                return;

            var universe = HopelessGame.Universe;
            var keyboard = Keyboard.GetState();

            if (keyboard.IsKeyDown(Keys.Escape) && !_lastKeyboardState.IsKeyDown(Keys.Escape))
                _game.Paused = !_game.Paused;

            if (_game.Paused)
            {
                _lastKeyboardState = keyboard;
                return;
            }

            if (universe.Hero == null)
            {
                _lastKeyboardState = keyboard;
                return;
            }

            var pressingA = keyboard.IsKeyDown(Keys.A);
            var pressingD = keyboard.IsKeyDown(Keys.D);
            var pressingW = keyboard.IsKeyDown(Keys.W);
            var pressingS = keyboard.IsKeyDown(Keys.S);

            var off = Vector2.Zero;

            if (pressingW && pressingA)
                off += new Vector2(-0.707f, -0.707f);
            if (pressingA && pressingS)
                off += new Vector2(-0.707f, 0.707f);
            if (pressingS && pressingD)
                off += new Vector2(0.707f, 0.707f);
            if (pressingD && pressingW)
                off += new Vector2(0.707f, -0.707f);
            if (pressingW && !pressingD && !pressingA)
                off += new Vector2(0f, -1f);
            if (pressingA && !pressingW && !pressingS)
                off += new Vector2(-1f, 0f);
            if (pressingS && !pressingA && !pressingD)
                off += new Vector2(0f, 1f);
            if (pressingD && !pressingS && !pressingW)
                off += new Vector2(1f, 0f);

            if (off != Vector2.Zero)
                universe.Hero.Walk(off);
            
            var mouse = Mouse.GetState();
            universe.Hero.FacingAngle = (float)GeometricAlgebra.GetAngleBetweenVectors(universe.Hero.Position, new Vector2(mouse.X, mouse.Y));

            if (mouse.LeftButton == ButtonState.Pressed || keyboard.IsKeyDown(Keys.Space))
                universe.Hero.SwingSword();

            _lastKeyboardState = keyboard;
        }
    }
}
